import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/bean/bean_tools_item.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/bean/event_bus_select_tool_category.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/widget/widget_tools_dialog.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/widget/widget_tools_editItem.dart';

typedef ItemTapCallBack = void Function(ToolsItem item); //点击减号，修改页面状态

//我的常用工具模块
class ToolsDragSortWidget extends StatefulWidget {
  final List<ToolsItem> data;
  final bool status; //状态0标识普通，1标识编辑中状态
  final EventBus eventBus;
  final ItemTapCallBack onTap;
  ToolsDragSortWidget(this.data, this.eventBus,
      {this.status = false, this.onTap});
  @override
  _ToolsDragSortWidgetState createState() => _ToolsDragSortWidgetState();
}

class _ToolsDragSortWidgetState extends State<ToolsDragSortWidget> {
  ToolsItem _draggingData; // 记录正在移动的值
  bool editStatus;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    editStatus = widget.status;
    return Center(
      child: Container(
        width: 375,
        padding: EdgeInsets.only(bottom: 24),
        child: GridView(
          shrinkWrap: true,
          padding: EdgeInsets.symmetric(horizontal: 16),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              mainAxisSpacing: 20,
              crossAxisSpacing: 0.0,
              childAspectRatio: 1.15),
          children: buildItems(),
          physics: NeverScrollableScrollPhysics(), //禁止滚动
        ),
      ),
    );
  }

  List<Widget> buildItems() {
    List<Widget> items = List<Widget>();
    // widget.data.forEach((item) {
    //   items.add(draggableItem(item));
    // });
    int length = widget.data.length;
    int mexLength = length > 8 ? 8 : length; //常用工具最大数量限制为8个
    for (var i = 0; i < mexLength; i++) {
      ToolsItem item = widget.data[i];
      items.add(draggableItem(item, i));
    }
    if (length > 4 && length < 8) {
      items
          .add(draggableItem(widget.data[length - 1], length)); //最近的一个空位置添加拖动元素
    }
    return items;
  }

  Widget draggableItem(value, int itemIndex) {
    return LongPressDraggable(
      data: value,
      dragAnchor: DragAnchor.child,
      maxSimultaneousDrags: _draggingData == null ? 1:0,
      child: DragTarget(
        builder: (context, candidateData, rejectedData) {
          if (itemIndex == widget.data.length) {
            return SizedBox();
          } else {
            return _buildToolItem(value, 2);
          }
        },
        onWillAccept: (moveData) {
          // print('=== onWillAccept: ${moveData.title} ==> ${value.title}');
          var accept = moveData != null;
          if (accept) {
            reorderItem(moveData, value, false);
          }
          return accept;
        },
        onAccept: (moveData) {
          // print('=== onAccept: ${moveData.title} ==> ${value.title}');
          reorderItem(moveData, value, true);
        },
        onLeave: (moveData) {},
      ),
      feedback: _buildToolItem(value, 1),
      childWhenDragging: null,
      onDragStarted: () {
        setState(() {
          _draggingData = value;
        });
        widget.eventBus?.fire(ToolsEditStatusEvent(true)); //长按开始拖动，修改父级页面编辑状态
      },
      onDraggableCanceled: (Velocity velocity, Offset offset) {
        setState(() {
          _draggingData = null;
        });
      },
      onDragCompleted: () {},
    );
  }

  Widget _buildToolItem(item, int index) {
    if (item == _draggingData) {
      return SizedBox();
    }
    editStatusType type;
    if (editStatus == false) {
      type = editStatusType.editStatusTypeNone;
    } else {
      type = editStatusType.editStatusTypeSub;
    }
    Widget _getItemContainer() {
      return Container(
        width: (375 - 32) / 4,
        child: Material(
          color: Colors.white,
          child: EditToolItemWidget(item, editType: type,
              tapCallback: (ToolsItem item, editStatusType type) {
            if (type == editStatusType.editStatusTypeSub) {
              //编辑状态，点击进行编辑操作
              setState(() {
                int index = widget.data.indexOf(item);
                widget.data.removeAt(index);
              });
              widget.eventBus?.fire(ToolsEditResultEvent(type, item));
            } else {
              //非编辑状态，点击跳转路由
              widget.onTap(item);
            }

            print('点击事件${item.title}');
          }),
        ),
      );
    }

    if (index == 1) {
      //长按编辑，状态变为删减
      type = editStatusType.editStatusTypeSub;
      return Transform.translate(
        offset: Offset(10, 10),  //长按的widget位置偏移效果
        child: _getItemContainer(),
      );
    }
    return _getItemContainer();
  }

  // 重新排序
  void reorderItem(moveData, toData, onAccept) {
    setState(() {
      var toIndex = widget.data.indexOf(toData);
      print('toIndex = $toIndex');
      widget.data.remove(moveData);
      widget.data.insert(toIndex, moveData);

      if (onAccept) {
        _draggingData = null;
      }
    });
  }
}

//更多工具业务线底下工具列表内容
class ToolsCategoryContentWidget extends StatefulWidget {
  final List<ToolsItem> data; //列表数据
  final bool status; //0标识普通状态，1标识编辑状态
  final EventBus eventBus;
  final ItemTapCallBack onTap;
  final commonToolsCount;
  ToolsCategoryContentWidget(this.data, this.eventBus,
      {this.status = false, this.commonToolsCount, this.onTap, key})
      : super(key: key);

  _ToolsCategoryContentWidgetState createState() =>
      _ToolsCategoryContentWidgetState();
}

class _ToolsCategoryContentWidgetState
    extends State<ToolsCategoryContentWidget> {
  List<ToolsItem> list;
  bool editStatus;
  editStatusType editType;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    list = widget.data;
    editStatus = widget.status;
    if (editStatus == false) {
      editType = editStatusType.editStatusTypeNone;
    } else {
      editType = editStatusType.editStatusTypeAdd;
    }
    return Container(
        width: 375,
        padding: EdgeInsets.only(top: 33,bottom:24 ),
        child: GridView.builder(
          shrinkWrap: true,
          padding: EdgeInsets.symmetric(horizontal: 16),
          itemCount: list?.length ?? 0,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              mainAxisSpacing: 20,
              crossAxisSpacing: 0.0,
              childAspectRatio: 1.15),
          itemBuilder: (context,index){
            return buildItems(context)[index];
          },
          physics: NeverScrollableScrollPhysics(), //禁止滚动
        ));
  }

  List<Widget> buildItems(BuildContext context) {
    List<Widget> widgets = new List();
    for (var i = 0; i < list.length; i++) {
      widgets.add(EditToolItemWidget(list[i], editType: editType,
          tapCallback: (ToolsItem item, editStatusType type) {
        if (type == editStatusType.editStatusTypeAdd) {
          if (widget.commonToolsCount == 8) {
            showTipDialog(context);
            return;
          }
          //编辑状态，点击执行编辑操作
          widget.eventBus?.fire(ToolsEditResultEvent(type, item));
        } else {
          //非编辑状态，点击执行跳转路由
          widget.onTap(item);
        }
      }));
    }
    return widgets;
  }

  void showTipDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return ToolsEditDialog(
            message: '常用工具已经够多啦，\n删除后再添加吧！',
          );
        });
  }
}
